import { View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useRef } from 'react'
import utils from '@/utils'
import BtLayout from '@/BtComponents/BtLayout'
import BtScroll from '@/BtComponents/BtScroll'
import { Button } from "@taroify/core"
import BtCustomForm, { FormItemType, FormItemConfig } from '@/BtComponents/BtCustomForm'
import useCreateStaffQrcodeStore, { setFormData, rules } from '../useCreateStaffQrcodeStore'
import './index.scss'

function RecConfigPage() {
  const formRef = useRef<any>(null)
  const form = useCreateStaffQrcodeStore(state => state.formData)
  const configForm = useCreateStaffQrcodeStore(state => state.formData.recConfig)
  const selector = [{id: '1', name: '是'}, {id: '2', name: '否'}]

  const formConfig: FormItemConfig[] = [
    {
      type: FormItemType.SWITCH,
      label: '海报样式',
      enableProp: 'enablePageStye',
      children: [
        {
          type: FormItemType.UPLOAD,
          prop: 'pageStye',
          placeholder: '请上传海报背景图'
        }
      ]
    },
    {
      type: FormItemType.PICKER,
      label: '老客户判定',
      prop: 'oldCustomerType',
      selector: selector,
      iconRemark: '扫码客户是否为企业老客户'
    },
    {
      type: FormItemType.PICKER,
      label: '扫码打开小程序',
      prop: 'scanCodeToOpen',
      selector: selector,
      iconRemark: '客户扫码后是否打开小程序'
    },
    {
      type: FormItemType.PICKER,
      label: '客户标签',
      prop: 'tags',
      selector: selector,
      iconRemark: '为扫码客户打上标签'
    }
  ]

  useLoad(async () => {
    await utils.$initPage()
  })

  const handleChange = (value: any, key: string) => {
    setFormData({
      ...form,
      recConfig: {
        ...configForm,
        [key]: value
      }
    })
  }

  const handleSubmit = async () => {
    const errors = await formRef.current.validate()
    if (!errors) {
      utils.$toast('配置成功')
      // 返回上一页
      Taro.navigateBack()
    }
  }

  return (
    <BtLayout
      config={{
        title: '识客配置'
      }}
    >
      <View className='rec-config flex flex-col'>
        <BtScroll>
          <BtCustomForm
            config={formConfig}
            model={configForm}
            onChange={handleChange}
            rules={rules}
            ref={formRef}
          />
        </BtScroll>
        <View className='submit-button'>
          <Button
            color='primary'
            block
            onClick={handleSubmit}
          >
            确定
          </Button>
        </View>
      </View>
    </BtLayout>
  )
}

export default RecConfigPage
